import { http } from '@/utils/request'
import type { 
  ApiResponse,
  User,
  UserStats,
  PaginationResult,
  RankingUser,
  Submission
} from '@/types'

/**
 * 用户API
 */
export const userApi = {
  // 获取用户信息（用于首页展示）
  getUserInfo(): Promise<ApiResponse<{
    username: string
    email: string
    avatar_url: string
    completed_questions: number
    accuracy: number
    contests_count: number
    ranking: number
  }>> {
    return http.get('/v1/user_info')
  },

  // 获取用户详细资料
  getUserProfile(userId: number): Promise<ApiResponse<User & { stats?: UserStats }>> {
    return http.get(`/v1/users/${userId}/profile`)
  },

  // 更新用户资料
  updateUserProfile(userId: number, data: {
    real_name?: string
    student_id?: string
    major?: string
    grade?: number
    school?: string
  }): Promise<ApiResponse<void>> {
    return http.put(`/v1/users/${userId}/profile`, data)
  },

  // 获取用户头像
  getUserAvatar(userId: number): string {
    return `${import.meta.env.VITE_API_BASE_URL}/v1/avatar/${userId}`
  },

  // 上传用户头像
  uploadAvatar(userId: number, file: File): Promise<ApiResponse<{ avatar_url: string }>> {
    return http.upload(`/v1/users/${userId}/avatar`, file)
  },

  // 获取用户排行榜
  getUserRanking(params: {
    page?: number
    page_size?: number
  } = {}): Promise<ApiResponse<PaginationResult<RankingUser>>> {
    return http.get('/v1/users/ranking', { params })
  },

  // 获取用户提交记录
  getUserSubmissions(userId: number, params: {
    page?: number
    page_size?: number
  } = {}): Promise<ApiResponse<PaginationResult<Submission>>> {
    return http.get(`/v1/users/${userId}/submissions`, { params })
  },

  // 获取用户统计信息
  getUserStats(userId: number): Promise<ApiResponse<UserStats>> {
    return http.get(`/v1/users/${userId}/stats`)
  },

  // 获取当前用户统计信息
  getCurrentUserStats(): Promise<ApiResponse<{
    solved_count: number,
    total_submissions: number,
    accepted_submissions: number,
    acceptance_rate: number,
    consecutive_days: number,
    difficulty_stats: {
      easy_solved: number,
      medium_solved: number,
      hard_solved: number
    }
  }>> {
    return http.get('/v1/users/stats')
  },

  // 获取用户解题日历
  getUserSolveCalendar(userId: number, year?: number): Promise<ApiResponse<{
    [date: string]: number // 日期 -> 解题数量
  }>> {
    const params = year ? { year } : {}
    return http.get(`/v1/users/${userId}/solve-calendar`, { params })
  },

  // 关注用户
  followUser(userId: number): Promise<ApiResponse<void>> {
    return http.post(`/v1/users/${userId}/follow`)
  },

  // 取消关注用户
  unfollowUser(userId: number): Promise<ApiResponse<void>> {
    return http.delete(`/v1/users/${userId}/follow`)
  },

  // 获取用户关注列表
  getUserFollowing(userId: number, params: {
    page?: number
    page_size?: number
  } = {}): Promise<ApiResponse<PaginationResult<User>>> {
    return http.get(`/v1/users/${userId}/following`, { params })
  },

  // 获取用户粉丝列表
  getUserFollowers(userId: number, params: {
    page?: number
    page_size?: number
  } = {}): Promise<ApiResponse<PaginationResult<User>>> {
    return http.get(`/v1/users/${userId}/followers`, { params })
  },

  // 搜索用户
  searchUsers(params: {
    keyword: string
    page?: number
    page_size?: number
  }): Promise<ApiResponse<PaginationResult<User>>> {
    return http.get('/v1/users/search', { params })
  },

  // 获取用户个人设置
  getUserSettings(): Promise<ApiResponse<{
    email_notifications: boolean
    contest_reminders: boolean
    theme: 'light' | 'dark' | 'system'
    language: string
    timezone: string
  }>> {
    return http.get('/v1/users/settings')
  },

  // 更新用户个人设置
  updateUserSettings(data: {
    email_notifications?: boolean
    contest_reminders?: boolean
    theme?: 'light' | 'dark' | 'system'
    language?: string
    timezone?: string
  }): Promise<ApiResponse<void>> {
    return http.put('/v1/users/settings', data)
  },
  changeAvatar(data: FormData): Promise<ApiResponse<{message : string ,avatar_url: string }>> {
    return http.post('/v1/auth/change-avatar', data, {
      headers: {
        // 显式指定为 multipart/form-data，但不写 boundary（让浏览器自动填充）
        'Content-Type': 'multipart/form-data'
      }
    });
  }
}

